import { defineStore } from "pinia"
import { getDictMembersByKey as getDictMembersByKeyApi } from "@/apis/system/dict.js"
import { ElMessage } from 'element-plus'
import { hasPermi } from "@/assets/common/utils.js";

export const useDictStore = defineStore({
    id: "dict",
    state: () => ({
        caches: {}, // 字典成员缓存
    }),
    actions: {
        // 获取字典成员
        async getDictMembers(key) {
            if (this.caches.hasOwnProperty(key)) {
                // 缓存
                return this.caches[key]
            } else {
                if (!hasPermi(['enttp:dict:queryKey'])) {
                    ElMessage({ message: '暂无获取字典成员权限', type: "error" });
                    return []
                }
                // 无缓存，从接口获取
                const dictMember = await this.getDictMembersByKey(key)
                this.caches[key] = dictMember
                return dictMember
            }
        },
        // 通过接口获取字典成员
        async getDictMembersByKey(key) {
            const res = await getDictMembersByKeyApi({ key })
            if (res.data.code === 200) {
                const members = res.data.data
                members.forEach(item => {
                    const memberKey = Number(item.memberKey)
                    item.memberKey = Number.isNaN(memberKey) ? item.memberKey : memberKey
                })
                return members
            } else {
                ElMessage({ message: res.data.msg, type: "error" });
            }
        },
        // 根据字典key和字典成员值获取字典成员名称
        getDictMemberName(key, value) {
            const members = this.caches[key] || []
            const member = members.find(item => item.memberKey === value)
            return member ? member.memberName : null
        },
        // 清空字典缓存
        clearCaches() {
            this.caches = {}
        },
    }
})